package org.hry.socket.bio.longlink;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Desc
 * @Author houry
 * @Date 2021/2/25 13:59
 **/
public class TimeOutSocketServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);
        Socket socket = server.accept();
        socket.setSoTimeout(1000);
        socket.setKeepAlive(true);
        InputStream in = socket.getInputStream();
        // 用来缓存截取出来的报文信息
        StringBuilder cache = new StringBuilder();
        while (true){
            byte[] bytes = new byte[1];
            in.read(bytes);
            String msg = new String(bytes, 0, 1);
            if (!"|".equalsIgnoreCase(msg)) {
                cache.append(msg);
            }else{
                System.out.println("收到的信息为：" + cache.toString());
                // 清空之前的缓存数据，防止数据粘包，方便下次数据获取
                cache.delete(0, cache.toString().length());
            }
        }
    }
}
